<!-- 录音播放控件 -->
<template>
	<div id="WaveSurferAudio">
		<a-spin :spinning="audioLoading">
			<div id="audio"></div>
			<!-- 录音播放控件 -->
			<div class="audio-ctrl">
				<div @click="play">
					<a-tooltip placement="bottom" color="#fff">
						<template #title>
							<span style="color: #000">{{ isPlaying ? '暂停' : '播放' }}</span>
						</template>
						<CaretRightOutlined v-if="!isPlaying" />
						<PauseOutlined v-else />
					</a-tooltip>
					<a-tooltip placement="bottom" color="#fff">
						<template #title>
							<span style="color: #000">后退</span>
						</template>
						<BackwardOutlined @click="directionTo('reverse')" />
					</a-tooltip>
					<a-tooltip placement="bottom" color="#fff">
						<template #title>
							<span style="color: #000">快进</span>
						</template>
						<ForwardOutlined @click="directionTo('drive')" />
					</a-tooltip>
				</div>
				<span>{{ curTime }}&nbsp;/&nbsp;{{ duration }}</span>
				<span>
					<a-tooltip placement="bottom" color="#fff">
						<template #title>
							<span style="color: #000">下载</span>
						</template>
						<VerticalAlignBottomOutlined @click="downLoadAudio" />
					</a-tooltip>
					<a-popover title="倍速" placement="bottomRight" overlayClassName="speed-popover">
						<template #content>
							<p
								v-for="item in speedOptions"
								::key="item"
								class="speed-item"
								:class="item == speed ? 'active' : ''"
								@click="speedChange(item)"
							>
								{{ item }}X
							</p>
						</template>
						<span class="speed">{{ speed }}X</span>
					</a-popover>
				</span>
			</div>
		</a-spin>
	</div>
</template>
<script setup name="WaveSurferAudio">
	import WaveSurfer from 'wavesurfer.js'
	import TimelinePlugin from 'wavesurfer.js/dist/plugins/timeline.esm.js'
	import { onMounted, ref, onUnmounted } from 'vue'
	import dayjs from 'dayjs'
	// ===========================================DATA======================================================
	const props = defineProps({
		audioUrl: {
			type: String,
			required: true
		}
	})
	const emits = defineEmits(['timeUpdate'])
	let waveSurfer = ref(null)
	let isPlaying = ref(false) //是否播放
	const seconds = 3 //快进后退秒数
	let speed = ref(1) //倍速
	let speedOptions = [0.5, 1, 1.5, 2] //倍速选项
	let duration = ref('00:00')	//总时长
	let curTime = ref('00:00') //当前播放时长
	let timeInterval = ref(1) //时间间隔（秒）
	const audioLoading = ref(false)
	// ===========================================LIFECYCLE HOOKS===========================================
	onMounted(() => {
		audioLoading.value = true
		// const audio = new Audio('https://saas-cti.htrxcall.com/recfile40/20250603/202506031338269963934004711748929107.wav') //测试录音
		// const audio = new Audio('https://saas-cti.htrxcall.com/recfile40/20250623/202506230932581913644002291750642378.wav') //测试录音1
		const audio = new Audio(props.audioUrl)

		audio.addEventListener('canplay', () => {
			// 获取音频总时长（秒）
			const audioDuration = audio.duration
			duration.value = dayjs(audioDuration * 1000).format('mm:ss')
			// 计算时间间隔,防止时间刻度重叠，30秒作为基数，每超过30秒，时间间隔+1
			timeInterval.value = Math.ceil(audioDuration / 30)
			waveSurfer.value = WaveSurfer.create({
				container: '#audio',
				waveColor: '#91caff', //未播放颜色
				progressColor: '#3875F6', //已播放颜色
				cursorColor: '#0958d9', //标记线颜色
				cursorWidth: 3, //标记线宽度
				height: 50,
				barWidth: 2,
				barGap: 1,
				barRadius: 2,
				mediaControls: true,
				autoplay: false,
				normalize: true,
				mediaControls: false,
				// url: 'https://saas-cti.htrxcall.com/recfile40/20250603/202506031338269963934004711748929107.wav',
				// url: 'https://saas-cti.htrxcall.com/recfile40/20250623/202506230932581913644002291750642378.wav',
				url: props.audioUrl,
				plugins: [
					TimelinePlugin.create({
						timeInterval: timeInterval.value, //
						primaryLabelInterval: 60, // 主标签每1秒显示
						secondaryLabelInterval: timeInterval.value, // 次标签每2秒显示
						// 可选：自定义时间格式
						formatTimeCallback: (seconds) => {
							const date = new Date(0)
							date.setSeconds(seconds)
							return dayjs(date).format('mm:ss')
						},
						height: 20,
						style: {
							marginTop: '5px'
						},
						// 样式调整
						secondaryColor: 'rgba(0, 0, 0, 0.2)',
						secondaryFontColor: '#666'
					})
				]
			})
			audioLoading.value = false
			//更新当前播放时间
			waveSurfer.value.on('audioprocess', () => {
				curTime.value = dayjs(waveSurfer.value.getCurrentTime() * 1000).format('mm:ss')
				// 发送当前播放时间（毫秒）
				emits('timeUpdate', waveSurfer.value.getCurrentTime() * 1000)
			})
			//鼠标点击更新播放时间
			waveSurfer.value.on('seeking', () => {
				curTime.value = dayjs(waveSurfer.value.getCurrentTime() * 1000).format('mm:ss')
				// 发送当前播放时间（毫秒）
				emits('timeUpdate', waveSurfer.value.getCurrentTime() * 1000)
			})
			//播放完成,光标归位
			waveSurfer.value.on('finish', () => {
				isPlaying.value = false
				waveSurfer.value.seekTo(0)
			})
		})
	})
	onUnmounted(() => {
		waveSurfer.value.destroy()
	})
	// ===========================================METHODS==================================================
	const play = () => {
		waveSurfer.value.playPause()
		isPlaying.value = waveSurfer.value.isPlaying()
	}
	//快进后退
	const directionTo = (v) => {
		//快进后退但不暂停
		if (v === 'drive') {
			waveSurfer.value.skip(seconds)
		} else {
			waveSurfer.value.skip(-seconds)
		}
		// 手动触发时间更新事件，确保对话滚动
		emits('timeUpdate', waveSurfer.value.getCurrentTime() * 1000)
		if (waveSurfer.value.isPlaying()) {
			waveSurfer.value.playPause()
		}
	}
	const downLoadAudio = () => {
		// 下载音频
		// 通过waveSurfer实例获取音频URL
		if (waveSurfer.value && props.audioUrl) {
			// 创建一个临时的a标签来触发下载
			const link = document.createElement('a')
			link.href = props.audioUrl
			// 从URL中提取文件名
			const fileName = props.audioUrl.split('/').pop() || 'audio.wav'
			link.download = fileName
			document.body.appendChild(link)
			link.click()
			document.body.removeChild(link)
		}
	}
	const speedChange = (v) => {
		speed.value = v
		waveSurfer.value.setPlaybackRate(v)
	}
	// ===========================================REQUEST==================================================
</script>
<style lang="less" scoped>
	#WaveSurferAudio {
		#audio {
			width: 100%;
			height: 75px;
			margin-bottom: 10px;
		}
		.audio-ctrl {
			width: 100%;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 14px;
			.anticon,
			.speed {
				display: inline-block;
				width: 30px;
				height: 30px;
				border-radius: 50%;
				text-align: center;
				line-height: 30px;
				cursor: pointer;
			}
			.anticon:hover,
			.speed:hover {
				background: #e6e6e6;
				box-shadow: 0 0 10px #e6e6e6;
			}
		}
	}
</style>
<style lang="less">
	.speed-popover {
		.ant-popover-inner {
			width: 50px;
			padding: 10px 0;
			.ant-popover-title {
				display: none;
			}
			.speed-item {
				cursor: pointer;
				border-radius: 2px;
				text-align: center;
				padding: 5px 0;
				margin: 0;
				&:hover {
					background: #f7f6f6;
				}
			}
			.active {
				background: #f7f6f6;
				color: #5794f7;
			}
		}
	}
</style>
